import { post, get } from '@/utils/request'
import axios from 'axios'
import { getToken } from '@/utils/auth'

/**
 * 分页查询用户证书
 * @param data 查询参数
 */
export function fetchPaging(data) {
  return post('/exam/api/user/cert/paging', data)
}

/**
 * 查询用户证书列表
 * @param userId 用户ID
 * @param examId 考试ID
 */
export function fetchList(userId, examId) {
  let url = '/exam/api/user/cert/list'
  let params = []
  if (userId) {
    params.push(`userId=${userId}`)
  }
  if (examId) {
    params.push(`examId=${examId}`)
  }
  if (params.length > 0) {
    url += '?' + params.join('&')
  }
  return get(url)
}

/**
 * 手动生成证书
 * @param userId 用户ID
 * @param examId 考试ID
 * @param certId 证书模板ID
 */
export function manualGenerate(userId, examId, certId) {
  return post(`/exam/api/user/cert/manual?userId=${userId}&examId=${examId}&certId=${certId}`)
}

/**
 * 为考试通过的用户创建证书生成任务
 * @param examId 考试ID
 */
export function createCertTasks(examId) {
  return post(`/exam/api/user/cert/createTasks/${examId}`)
}

/**
 * 下载证书文件
 * @param certId 用户证书ID
 */
export function downloadCert(certId) {
  return get(`/exam/api/user/cert/download/${certId}`)
}

/**
 * 批量操作证书
 * @param ids 证书ID列表
 * @param action 操作类型：regenerate-重新生成
 */
export function batchAction(ids, action) {
  return post('/exam/api/user/cert/batch-action', {
    ids,
    action
  })
}

/**
 * 删除单个用户证书
 * @param userId 用户ID
 * @param examId 考试ID
 * @param certId 证书模板ID
 */
export function deleteUserCertificate(userId, examId, certId) {
  return axios({
    url: process.env.VUE_APP_BASE_API + '/exam/api/user/cert/delete',
    method: 'delete',
    headers: {
      'token': getToken()
    },
    params: {
      userId,
      examId,
      certId
    }
  })
}

/**
 * 批量删除指定考试的所有证书
 * @param examId 考试ID
 */
export function deleteAllCertificatesByExam(examId) {
  return axios({
    url: process.env.VUE_APP_BASE_API + `/exam/api/user/cert/deleteByExam/${examId}`,
    method: 'delete',
    headers: {
      'token': getToken()
    }
  })
}
